<template>
  <div class="profile-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <el-button 
            type="text" 
            @click="$router.back()" 
            class="back-button"
          >
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
          <h1>个人资料</h1>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="handleSave" :loading="saving">
            <el-icon><Check /></el-icon>
            保存修改
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 主要内容 -->
    <div class="profile-content">
      <div class="content-wrapper">
        <!-- 头像区域 -->
        <div class="avatar-section">
          <div class="avatar-card">
            <div class="avatar-container">
              <img 
                :src="userForm.avatar || '/OIP.webp'" 
                alt="用户头像" 
                class="user-avatar"
              />
              <div class="avatar-overlay" @click="handleAvatarClick">
                <el-icon size="24"><Camera /></el-icon>
                <span>更换头像</span>
              </div>
            </div>
            <div class="user-basic-info">
              <h2>{{ userForm.realName || userForm.username }}</h2>
              <p class="user-id">ID: {{ userForm.id }}</p>
              <div class="user-status">
                <el-tag type="success" size="small">
                  <el-icon><CircleCheck /></el-icon>
                  已认证
                </el-tag>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 表单区域 -->
        <div class="form-section">
          <div class="form-card">
            <div class="card-header">
              <h3><el-icon><User /></el-icon>基本信息</h3>
            </div>
            <div class="card-content">
              <el-form
                ref="profileFormRef"
                :model="userForm"
                :rules="formRules"
                label-width="100px"
                class="profile-form"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="用户名" prop="username">
                      <el-input
                        v-model="userForm.username"
                        placeholder="请输入用户名"
                        :disabled="true"
                      >
                        <template #prefix>
                          <el-icon><User /></el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="真实姓名" prop="realName">
                      <el-input
                        v-model="userForm.realName"
                        placeholder="请输入真实姓名"
                      >
                        <template #prefix>
                          <el-icon><UserFilled /></el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="手机号" prop="phone">
                      <el-input
                        v-model="userForm.phone"
                        placeholder="请输入手机号"
                      >
                        <template #prefix>
                          <el-icon><Phone /></el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="邮箱" prop="email">
                      <el-input
                        v-model="userForm.email"
                        placeholder="请输入邮箱地址"
                      >
                        <template #prefix>
                          <el-icon><Message /></el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="性别">
                      <el-radio-group v-model="userForm.gender">
                        <el-radio label="male">男</el-radio>
                        <el-radio label="female">女</el-radio>
                        <el-radio label="other">其他</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="出生日期">
                      <el-date-picker
                        v-model="userForm.birthDate"
                        type="date"
                        placeholder="选择出生日期"
                        style="width: 100%"
                        :disabled-date="disabledDate"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-form-item label="个人简介">
                  <el-input
                    v-model="userForm.bio"
                    type="textarea"
                    :rows="4"
                    placeholder="介绍一下自己吧..."
                    maxlength="200"
                    show-word-limit
                  />
                </el-form-item>
              </el-form>
            </div>
          </div>
          
          <!-- 安全设置卡片 -->
          <div class="form-card">
            <div class="card-header">
              <h3><el-icon><Lock /></el-icon>安全设置</h3>
            </div>
            <div class="card-content">
              <div class="security-items">
                <div class="security-item">
                  <div class="security-info">
                    <div class="security-title">登录密码</div>
                    <div class="security-desc">定期更换密码，保护账户安全</div>
                  </div>
                  <el-button type="primary" text @click="showChangePassword">
                    修改密码
                  </el-button>
                </div>
                
                <div class="security-item">
                  <div class="security-info">
                    <div class="security-title">手机绑定</div>
                    <div class="security-desc">{{ userForm.phone || '未绑定手机号' }}</div>
                  </div>
                  <el-button type="primary" text>
                    {{ userForm.phone ? '更换手机' : '绑定手机' }}
                  </el-button>
                </div>
                
                <div class="security-item">
                  <div class="security-info">
                    <div class="security-title">邮箱绑定</div>
                    <div class="security-desc">{{ userForm.email || '未绑定邮箱' }}</div>
                  </div>
                  <el-button type="primary" text>
                    {{ userForm.email ? '更换邮箱' : '绑定邮箱' }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 偏好设置卡片 -->
          <div class="form-card">
            <div class="card-header">
              <h3><el-icon><Setting /></el-icon>偏好设置</h3>
            </div>
            <div class="card-content">
              <div class="preference-items">
                <div class="preference-item">
                  <div class="preference-info">
                    <div class="preference-title">消息通知</div>
                    <div class="preference-desc">接收系统消息和健康提醒</div>
                  </div>
                  <el-switch v-model="preferences.notifications" />
                </div>
                
                <div class="preference-item">
                  <div class="preference-info">
                    <div class="preference-title">邮件推送</div>
                    <div class="preference-desc">接收预约提醒和健康资讯邮件</div>
                  </div>
                  <el-switch v-model="preferences.emailNotifications" />
                </div>
                
                <div class="preference-item">
                  <div class="preference-info">
                    <div class="preference-title">数据分析</div>
                    <div class="preference-desc">允许分析使用数据以改善服务</div>
                  </div>
                  <el-switch v-model="preferences.dataAnalytics" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
      :before-close="handleClosePasswordDialog"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="passwordForm.currentPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">
          确定修改
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 隐藏的文件输入 -->
    <input
      ref="fileInputRef"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleAvatarChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  Check,
  Camera,
  CircleCheck,
  User,
  UserFilled,
  Phone,
  Message,
  Lock,
  Setting
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const profileFormRef = ref()
const passwordFormRef = ref()
const fileInputRef = ref()
const saving = ref(false)
const passwordDialogVisible = ref(false)
const changingPassword = ref(false)

// 用户表单数据
const userForm = reactive({
  id: userStore.userInfo?.id || '',
  username: userStore.userInfo?.username || '',
  realName: userStore.userInfo?.realName || '',
  phone: userStore.userInfo?.phone || '',
  email: userStore.userInfo?.email || '',
  gender: userStore.userInfo?.gender || '',
  birthDate: userStore.userInfo?.birthDate || null,
  bio: userStore.userInfo?.bio || '',
  avatar: userStore.userInfo?.avatar || '/OIP.webp'
})

// 偏好设置
const preferences = reactive({
  notifications: true,
  emailNotifications: true,
  dataAnalytics: false
})

// 密码修改表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const formRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 禁用未来日期
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

// 保存用户信息
const handleSave = async () => {
  if (!profileFormRef.value) return
  
  try {
    const valid = await profileFormRef.value.validate()
    if (!valid) return
    
    saving.value = true
    const result = await userStore.updateUserInfo(userForm)
    
    if (result.success) {
      ElMessage.success('个人资料保存成功！')
    } else {
      ElMessage.error(result.message || '保存失败，请稍后重试')
    }
  } catch (error) {
    console.error('保存用户信息失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  } finally {
    saving.value = false
  }
}

// 显示修改密码对话框
const showChangePassword = () => {
  passwordDialogVisible.value = true
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    const valid = await passwordFormRef.value.validate()
    if (!valid) return
    
    changingPassword.value = true
    
    // TODO: 调用后端API修改密码
    // const result = await api.changePassword(passwordForm)
    
    // 模拟成功
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('密码修改成功！')
    passwordDialogVisible.value = false
    
    // 重置表单
    passwordForm.currentPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败，请稍后重试')
  } finally {
    changingPassword.value = false
  }
}

// 关闭密码对话框
const handleClosePasswordDialog = () => {
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = false
}

// 点击头像
const handleAvatarClick = () => {
  fileInputRef.value?.click()
}

// 头像文件改变
const handleAvatarChange = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }
  
  // 验证文件大小（2MB）
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过2MB')
    return
  }
  
  // 创建预览
  const reader = new FileReader()
  reader.onload = (e) => {
    userForm.avatar = e.target.result
    ElMessage.success('头像已更新，请保存修改')
  }
  reader.readAsDataURL(file)
  
  // 清空input值，允许重复选择同一文件
  event.target.value = ''
}

onMounted(() => {
  // 初始化数据
  if (userStore.userInfo) {
    Object.assign(userForm, userStore.userInfo)
  }
})
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background: #f5f7fa;
}

.page-header {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #409eff;
}

.header-left h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.profile-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.content-wrapper {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 30px;
}

.avatar-section {
  position: sticky;
  top: 100px;
  height: fit-content;
}

.avatar-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-bottom: 20px;
}

.user-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #f0f0f0;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
  gap: 5px;
}

.avatar-overlay span {
  font-size: 12px;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.user-basic-info h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
}

.user-id {
  margin: 0 0 15px 0;
  color: #909399;
  font-size: 14px;
}

.form-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.card-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-content {
  padding: 20px;
}

.security-items,
.preference-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.security-item,
.preference-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.security-title,
.preference-title {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.security-desc,
.preference-desc {
  font-size: 12px;
  color: #7f8c8d;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .content-wrapper {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .avatar-section {
    position: static;
  }
  
  .avatar-card {
    display: flex;
    align-items: center;
    text-align: left;
    gap: 20px;
  }
  
  .user-avatar {
    width: 80px;
    height: 80px;
  }
}

@media (max-width: 768px) {
  .profile-content {
    padding: 20px 15px;
  }
  
  .avatar-card {
    flex-direction: column;
    text-align: center;
  }
  
  .header-content {
    padding: 0 10px;
  }
  
  .header-left h1 {
    font-size: 20px;
  }
}
</style>